package com.material.c2c.classify.service;

import java.util.ArrayList;
import java.util.List;

import javax.annotation.Resource;
import javax.transaction.Transactional;

import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;

import com.cpt.framework.core.OperationResult;
import com.material.c2c.classify.dao.ClassifyDao;
import com.material.c2c.classify.entity.SPFL;
import com.material.c2c.classify.model.ClassifyDTO;
import com.material.c2c.classify.model.ClassifyTreeNode;
import com.material.c2c.core.UUIDGenerator;
import com.material.c2c.util.BeanUtils;

/**
 * 分类查询接口
 * @author Administrator
 *
 */
@Service
public class ClassifyServiceImpl implements ClassifyService {
	@Resource
	private ClassifyDao classifyDao;
	
	
	@Override
	public OperationResult add(SPFL spfl) {
	    //设置id
	    spfl.setId(UUIDGenerator.generateUUIDStr());
	    SPFL fl = new SPFL();
	    BeanUtils.copyBeanNotNull2Bean(spfl, fl);
	    fl = classifyDao.add(fl);
		if(fl == null) {
			return OperationResult.failed("分类添加失败！");
		}
		return OperationResult.SUCCEED;
	}
	@Transactional
	@Override
	public OperationResult delete(String flid) {
		int xjfl =classifyDao.countByPid(flid);
		if(xjfl > 0) {
			return OperationResult.failed("存在下级分类不能删除！");
		}
		classifyDao.delete(flid);
		return OperationResult.SUCCEED;
	}
	@Transactional
	@Override
	public OperationResult update(ClassifyDTO dto) {
		classifyDao.update(dto);
		return OperationResult.SUCCEED;
	}
	@Override
	public SPFL getOne(String id) {
	  return classifyDao.getOne(id);
	}
	@Override
	public List<ClassifyTreeNode> createTree() {
		// 顶级菜单列表
		List<ClassifyTreeNode> nodeTree = new ArrayList<ClassifyTreeNode>();
		// 分类列表
		List<SPFL> classifyList = classifyDao.listAll();
		// 创建菜单树
		createChild(classifyList,nodeTree,null);
		return nodeTree;
	}
	@Override
	public Page<ClassifyDTO> search(Pageable request, String pid, String key){
		// 分页查询分类信息
		return classifyDao.findByPid(request, pid, key);
	}
	@Override
	public Page<ClassifyDTO> page(Pageable request, String key){
		// 分页查询分类信息
		return classifyDao.findAll(request);
	}
	// 创建菜单树
	private void createChild(List<SPFL> classifyList, List<ClassifyTreeNode> nodeTree,
			String nodeId) {
		for(SPFL spfl:classifyList) {
			boolean equalNode = false;
			if(nodeId == null) {
				equalNode = nodeId == spfl.getPid();
			}else {
				equalNode = nodeId.equals(spfl.getPid());
			}
			if(equalNode) {
				ClassifyTreeNode child = new ClassifyTreeNode(spfl);
				createChild(classifyList,child.getChildren(),spfl.getId());
				nodeTree.add(child);
			}
		}
	}
}
